<?php

namespace App\Http\Middleware;

use App\Http\Model\Admin_user;
use App\Http\Requests\Request;
use Closure;

class HasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

//        根据当前的登录用户获取到属于该用户的角色
      $roles =  Admin_user::find(session('usersession')->id)->roles()->get();

      // 声明存放权限的数组
        $arr = [];
        foreach($roles as $k=>$v){
           $p =  $v->permissions()->get();
           foreach($p as $m=>$n){
               $arr[] = $n->name;
           }
        }
       $prems =  array_unique($arr);

//        根据获取的角色获取属于该角色的权限


//        获取当前路由"App\Http\Controllers\Admin\IndexController@index"
        $route =   \Route::current()->getActionName();
//        dd($route);

//        判断当前路由是否在权限列表中，在就继续，不在返回
        if(!in_array($route,$prems)){
            return redirect('hasnorole');
        }


        return $next($request);
    }
}
